<template>
  <div class="container">
    <layout-card
      v-model="search"
      :filters="isExampleOptions"
      headline="数据筛选"
      :hasButton="false"
    >
      <el-form  ref="retrievedFormRef" :model="retrievedForm" :rules="rules" label-position="right">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="文件名称：" prop="receiveTime" label-width="100px">
              <el-input v-model="retrievedForm.fileName" placeholder="请输入文件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文件编号：" prop="receiveName" label-width="100px">
              <el-input v-model="retrievedForm.code" placeholder="请输入文件编号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文件版本：" prop="receiveName" label-width="100px">
              <el-input v-model="retrievedForm.versionNumber" placeholder="支持模糊搜索" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文件类型：" prop="receiveName" label-width="100px">
              <el-select v-model="retrievedForm.enclosureType" placeholder="请选择">
                <el-option
                  v-for="item in fileTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建者：" prop="receiveName" label-width="100px">
              <el-input v-model="retrievedForm.creator" placeholder="支持模糊搜索" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间：" prop="receiveName" label-width="100px">
              <div class="demo-range">
                <el-date-picker
                  v-model="retrievedForm.timeStr"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  type="daterange"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="defaultTime"
                  :popper-options="popOptions"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div style="justify-content: flex-end;display: flex">
        <el-button @click="searchReset">清空</el-button>
        <el-button
          type="primary"
          @click="searchChange"
        >查询</el-button>
      </div>
    </layout-card>
    <div class="tableColumns">
      <div class="left-tree">
        <el-tree
          ref="treeRefs"
          :current-node-key="currentNodeKey"
          node-key="id"
          class="filter-tree"
          :data="companyData"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
          highlight-current
          v-loading="loadingTree"
        >
          <template #default="{ node, data }">
              <span class="span-ellipsis">
                <span>{{ node.label }}</span>
                </span>
          </template>
        </el-tree>
      </div>
      <div class="right-columns">
          <span class="title-span">
              <span>目录列表</span>
          </span>
        <div class="btn-box">
          <el-button
            type="primary"
            @click="exportFn"
            :loading="exportLoading1"
            :disabled="tableData.length>0 ? false :true"
          >导出</el-button>
          <el-button
            type="primary"
            @click="fileTransfer()"
            :disabled="copybtnFlag"
          >复制</el-button>
          <el-popconfirm title="是否删除?"  @confirm="() => shanchu()">
            <template #reference>
              <el-button type="danger" :disabled="copybtnFlag">删除</el-button>
            </template>
          </el-popconfirm>

          <el-button
            type="primary"
            @click="openUploadDialog()"
            :disabled="showBtn"
          >上传文件</el-button>
        </div>
        <table-common
          :loading="loading"
          :columns="exampleColumns"
          :pagination="pager"
          :table-data="tableData"
          size="small"
          @sort-change="sortChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @select="handleSelect"
          @select-all="handleSelectAll"
          stripe
          style="width: 100%;margin-top: 15px;"
          :height="'400px'"
        >
          <template #action="{ row }">
            <!-- 自定义操作栏示例  -->
            <el-button
              class="link-btn"
              @click="handlePre(row)"
              link
              type="primary"
            >预览</el-button>
           <el-button
              class="link-btn"
              @click="download(row)"
              link
              type="primary"
            >下载</el-button>

            <el-button
              class="link-btn"
              @click="handleEdit(row)"
              link
              type="primary"
            >编辑</el-button>

            <el-popconfirm title="是否删除?"  @confirm="() => handleDel(row)">
              <template #reference>
                <el-button
                  class="link-btn"
                  link
                  type="primary"
                >删除</el-button>
              </template>
            </el-popconfirm>
            <el-button
              class="link-btn"
              @click="handleHistory(row)"
              link
              type="primary"
            >历史版本</el-button>
          </template>
        </table-common>
      </div>
    </div>
    <!--  复制---文件转移弹窗    -->
    <edit-dialog
      class="maintenance"
      :centerDialogVisible="transferDialogVisible"
      :tilte="addTransferTilte"
      :key="timer"
      :defaultButton="false"
      :width="500"
      @cancel="handleCancel"
      :close-on-click-modal="false"
    >
      <template #content>
        <el-tree
          ref="treeRef1"
          class="filter-tree"
          :data="companyData"
          :props="defaultProps"
          default-expand-all
          node-key ="id"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          @check-change="handleNodeClick1"
          show-checkbox
          :check-strictly="true"
        ></el-tree>
      </template>
      <template #custom>
              <span class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleTransferSubmit">保存</el-button>
              </span>
      </template>
    </edit-dialog>
<!--    文佳上传弹窗-->
    <edit-dialog :centerDialogVisible="centerDialogVisible" :tilte="'文件上传'" @Cancel="handleCancel"
                 @Submit="handleSubmitFile" :width="dialogWidth" :defaultButton="false">
      <template #content>
        <el-upload
          class="upload-demo"
          drag
          action="#"
          multiple
          :auto-upload="false"
          :on-change="handleChangeFile"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            选择文件
          </div>

        </el-upload>
      </template>
      <template #custom>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmitFile"
                     :loading="exportLoading" :disabled="exportLoading"
          >确认</el-button>
        </span>
      </template>
    </edit-dialog>
<!--    历史版本-->
    <edit-dialog :centerDialogVisible="centerDialogVisible2" :tilte="'历史版本'" @Cancel="handleCancel"
                 @Submit="handleSubmitFile" :width="'50%'" :defaultButton="false">
      <template #content>
        <el-table ref="tableRef" :data="historyData" style="min-width: 100%;max-height: 300px;overflow-y: scroll">
          <el-table-column prop="index" type="index" label="序号" width="80"/>
          <el-table-column prop="enclosureName" label="文档名称" width="200"/>
          <el-table-column prop="enclosureVersion" label="版本号" width="200"/>
          <el-table-column prop="createTime" label="上传时间" width="200"/>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handlePre(scope.row)"
                       >预览
              </el-button>
              <el-button link type="primary" size="small" @click="download(scope.row)"
                         >下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </edit-dialog>
<!--    编辑文件-->
    <editFile :visible="addDialogVisible"  :goodsType="goodsTypeDatas" :info="fileInfo"  @cancel="handleCancel" @ok="submit"/>
    <el-image-viewer
      v-if="showViewer"
      @close="showViewer=false"
      :url-list="[fileUrl]"/>
    <preViewFile :visible="showFile" :fileType="fileType" :url="fileUrl" @cancel="showFile=false"></preViewFile>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, onBeforeMount, nextTick, watch, reactive, onMounted } from 'vue' // watch监听
  import {ElTree, ElMessage, UploadProps, dayjs} from 'element-plus'
  // 7-18修改LayoutCard 页面，hasButton参数为false时显示为弹窗样式，为true时显示为搜索栏样式
  import LayoutCard from '@/components/LayoutCard/index.vue'
  import TableCommon from '@/components/TableCommon/index.vue'
  import { exampleColumns, modelColumns } from './config/columns'
  import editDialog from '@/components/editDialog/index.vue'
  import {getResource} from "@/api/resource"
  import {useStore} from "vuex";
  import {getChildrenDirectory1} from "@/api/knowledge/space"
  import  preViewFile from '@/components/previewFile/index.vue'
  import {enclosurePageList, exportFile,addFiles,deleteFiles,getHistory,CopyFiles} from "@/api/knowledge/enclosure"
  import {eventRulesTemplateDownload} from "@/api/eventManage/eventRules";
  import {
    downloadFiles,
    onGetFileDownloadPath,
    preViewPdf,
    preViewPPTToPdf,
    uploadFiles,
    uploadKonwledgeFiles
  } from "@/api/common";
  import editFile from './editFile.vue'
  import {baseUrlConfig} from "@/config/config";
  const {getters} = useStore();
  const organizes1=computed(() => getters['user/getOrganTree']);
  const organizes = ref(JSON.parse(JSON.stringify(organizes1.value)));
  const userInfo = computed(() => getters['user/getUserInfo'])
  const copybtnFlag=ref(true)
  const fileUrl=ref()
  interface OrderItem {
    column?: string
    method?: string
  }
  const showViewer=ref(false)
  const order = ref([{"column": "create_time","method": "desc"}] as OrderItem[]);
  const retrievedForm = ref({
    fileName: undefined,
    versionNumber: undefined,
    fileCode: undefined,
    enclosureType: undefined,
    timeStr: [],
    directoryCode:undefined,
    enclosureClassification:1,
    name:''
  });
  const pager = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    pageCount: 0,
  });
  const defaultProps = {
    children: 'children',
    label: 'name',
  };
  const companyData = ref<any>([]); // 左侧树形数据
  const transferDialogVisible = ref(false);// 复制---转移弹窗
  const addTransferTilte = ref(""); // 转移弹窗名称
  const fileTypes=ref([]);
  const loading=ref(false);
  const tableData=ref([]);
  const doc = ref();
  //历史版本
  const historyData=ref([])
  //上传文件集合
  const fileList=ref<any>([])
  //是否打开文件上传弹窗
  const centerDialogVisible=ref(false)
  const centerDialogVisible1=ref(false)
  const centerDialogVisible2=ref(false)
  const addDialogVisible=ref(false)
  const fileInfo=ref();
  const defaultTime = [new Date(2000, 2, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];//选择日期后的默认时间
  const popOptions = { // 日期弹窗位置
   modifiers: [
        {
            name: 'flip',
            options: {
                fallbackPlacements: ['bottom'],
                allowedAutoPlacements: ['bottom'],
            }
        }
    ]
  }
  //默认选中组织目录第一个
  const currentNodeKey=ref("")
  const treeRefs=ref(null)
  const getTopOne=(data:any)=>{
    if(data.children&&data.children.length>0){
      getTopOne(data.children[0])
    }else{
      nextTick(()=>{
        currentNodeKey.value= data.id
        treeRefs.value.setCurrentKey(currentNodeKey.value)
        console.log(currentNodeKey.value)
        retrievedForm.value.directoryCode = data.id;
        retrievedForm.value.name = data.name;
        getList()
      })
    }
  }
  /**
   * 树形数据
   */
  const loadingTree=ref(false)
  const companyDataFn = async () => {
    companyData.value=[]
    const data= JSON.parse(JSON.stringify(organizes.value))
    loadingTree.value=true
    await ergodicTree(data)
    companyData.value=data
    getTopOne(companyData.value[0])
    loadingTree.value=false
  };
  const ergodicTree=async (datas: any) => {
    for (const item of datas) {
      if (item.children.length > 0) {
        item.name = item.organizationName
        await ergodicTree(item.children)
      } else {
        item.id = item.organizationId
        item.name = item.organizationName
        item.catalogueId = item.organizationId
        item.children = []
        await onGetSpaceList(item)
      }
    }
  };
  const onGetSpaceList= async (data: any) => {
    const res = await getChildrenDirectory1(data.id,1)
    if (res?.code == '1') {
      if (res.data.length > 0) {
        res.data.forEach((item: any) => {

          if (item.catalogueId == data.catalogueId) {
            data.children.push(item)
          }

        })
        console.log(companyData.value)

      }
    }
  }
  /**
   * 预览
   */
  const fileType=ref()
  const showFile=ref(false)
  const handlePre = (data: any) => {
    if (/(.jpg|.jpeg|.png|.gif|.bmp|.svg)/.test(data.path)) {
      fileUrl.value = data.path
      showViewer.value = true;
    } else {
      if(data.enclosureType=='doc'||data.enclosureType=='docx') {
        preViewPdf(data.enclosureCode).then(res => {
          console.log(res)
          const blob = new Blob([res], {type: "application/pdf"})
          fileUrl.value = URL.createObjectURL(blob)
          fileType.value = 'pdf'
          showFile.value = true
        })
      }else if(data.enclosureType=='pptx'||data.enclosureType=='ppt'){
        preViewPPTToPdf(data.enclosureCode).then(res => {
          console.log(res)
          const blob = new Blob([res], {type: "application/pdf"})
          fileUrl.value = URL.createObjectURL(blob)
          fileType.value = 'pdf'
          showFile.value = true
        })
      }else if(data.enclosureType=='pdf'){
        onGetFileDownloadPath(data.enclosureCode).then(res => {
          console.log(res)
          const blob = new Blob([res], {type: "application/pdf"})
          fileUrl.value = URL.createObjectURL(blob)
          fileType.value = 'pdf'
          showFile.value = true
        })
      }else{
        onGetFileDownloadPath(data.enclosureCode).then(res => {
          console.log(res)
          const blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})
          fileUrl.value = URL.createObjectURL(blob)
          fileType.value = 'xlsx'
          showFile.value = true
        })
      }
    }
  }
  const fileUrlOnlinePreview =(url:String, fileName:String) => {
    const typeArr = ["doc", "docx", "ppt", "pptx", "xls", "xlsx"];
    let arr = url.split(".");
    let fileType = arr[arr.length - 1];
    let downloadUrl = "";
    if (typeArr.indexOf(fileType) !== -1) {
      // 谷歌预览地址 https://docs.google.com/viewer?url=
      downloadUrl = "https://view.officeapps.live.com/op/view.aspx?src=" +url;
    } else {
      downloadUrl = url;
    }
    const width = 1000;
    const height = 800;
    const top = (window.screen.availHeight - height) / 2;
    const left = (window.screen.availWidth - width) / 2;
    const openObj = window.open(
      downloadUrl,
      "",
      "width=" + width + ",height=" + height + ",top=" + top + ",left=" + left
    );
    openObj.document.title = fileName;
  };

  //选择文件
  const selectFiles=ref([])
  const handleSelect=(row:any)=>{
    selectFiles.value=row
  }
  const handleSelectAll=(row:any)=>{
    selectFiles.value=row
  }
  watch(selectFiles, (val) => {
    if(val.length>0)copybtnFlag.value=false
    else copybtnFlag.value=true

  })
  /**
   * 文件转移按钮（复制）
   */
  const fileTransfer = async () => {
    if(selectFiles.value.length==0){
      ElMessage.error(`请先选择需要复制的文件`)
      return
    }
    addTransferTilte.value = "文件复制";
    transferDialogVisible.value = true;
  };
  // 批量文件删除
  const shanchu= async () => {
    loading.value=true
    const ids = selectFiles.value.map(item => item?.id)
    const data = {
      deleteUser: {
        id: userInfo.value.userId,
        name: userInfo.value.name,
        userName: userInfo.value.userName,
        organId: userInfo.value.organId || '',
        organName: userInfo.value.organName || ''
      },
      ids: ids
    }
    const res = await deleteFiles(data)
    if(res.code=='1'){
      ElMessage.success(`删除成功`)
      selectFiles.value=[];
      loading.value=false
      getList()
    }else{
      ElMessage.error(`删除失败`)
      loading.value=false
    }
  }
  const handleDel= async (row: any) => {
    const data = {
      deleteUser: {
        id: userInfo.value.userId,
        name: userInfo.value.name,
        userName: userInfo.value.userName,
        organId: userInfo.value.organId || '',
        organName: userInfo.value.organName || ''
      },
      ids: [row.id]
    }
    const res = await deleteFiles(data)
    if (res.code == '1') {
      ElMessage.success(`删除成功`)
      selectFiles.value = [];
      getList()
    } else {
      ElMessage.error(`删除失败`)
    }
  }
  /**
   * 取消按钮
   */
  const handleCancel = () => {
    transferDialogVisible.value = false;
    centerDialogVisible.value=false
    centerDialogVisible2.value=false
    centerDialogVisible1.value=false
    addDialogVisible.value=false
    fileList.value=[]
    exportLoading.value=false
    exportLoading1.value=false
    directoryCode.value=null
  };

  /**
   * 转移---保存按钮
   */
  const handleTransferSubmit = async () => {
    if(directoryCode.value==null){
      ElMessage.info(`请选择目录`)
      return
    }
    const ids = selectFiles.value.map(item => item?.id)
    const data = {
      creator: {
        id: userInfo.value.userId,
        name: userInfo.value.name,
        userName: userInfo.value.userName,
        organId: userInfo.value.organId || '',
        organName: userInfo.value.organName || ''
      },
      directoryCode: directoryCode.value,
      enclosureIds: ids
    }
    const res = await CopyFiles(data)
    if (res.code == '1') {
      ElMessage.success(`复制成功`)
      selectFiles.value = [];
      getList()
    } else {
      ElMessage.error(`复制失败`)
    }
    directoryCode.value=null
    transferDialogVisible.value = false;

  };
  // 编辑文件弹窗
  const handleEdit=(row:any)=>{
    addDialogVisible.value=true
    fileInfo.value=row;
  }
  //文件修改成功
  const submit=()=>{
    addDialogVisible.value=false
    getList()
  }
  /**
   * 打开上传文件弹窗
   */
  const openUploadDialog = () => {
    if(retrievedForm.value.directoryCode==undefined){
      ElMessage.error(`请先选择上传的文件目录`)
      return
    }
    console.log("开始上传文件");
    centerDialogVisible.value=true
    fileList.value=[]

  };
  const handleChangeFile: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    console.log('uploadFile',uploadFile)
    console.log('uploadFiles',uploadFiles)

    fileList.value = uploadFiles
  }
  //上传文件
  const handleSubmitFile= async () => {
    exportLoading.value=true
    const res = await getFiles();
    if(res.length==0){
      //ElMessage.error(`上传失败`)
      exportLoading.value=false
      return
    }else{
      addFiles(res).then((result: any) => {
        console.log(result)
        if(result.code=='1'){
          ElMessage.success(`上传成功`)
          exportLoading.value=false
          handleCancel()
          getList()
        }else{
          ElMessage.error(`上传失败`)
        }
      }).finally(()=>{
        exportLoading.value=false
      })
    }

  }
  //上传文件
  const getFiles = async () => {
    let files: Array<FileDataType> = []
    let len = fileList.value.length;
    for (let i = 0; i < len; i++) {
      let ele: any = fileList.value[i];
      const fileName = ele.name;
      const isSyncEs = 'true';
      const enclosureSize=ele.size
      const index = fileName.lastIndexOf('.')
      const name = fileName.slice(0, index)
      let formData = new FormData();
      formData.append('file', ele.raw)
      formData.append('fileName', name)
      formData.append('isSyncEs',isSyncEs);
      let res = null;
      try {
        res = await uploadKonwledgeFiles(formData)
      } catch {
        ElMessage.error(`${name}上传失败`)
      }
      if (res?.data) {
        files.push({
          enclosureContent: res.data.enclosureContent, // 文件名 TCDM.md
          enclosureName: res.data.enclosureName, // 文件前缀 TCDM
          enclosureType: res.data.enclosureSuffix, // 文件后缀md
          path: res.data.resourceAddress, // 文件相对地址，网关地址+resourceAddres即可完成下载
          enclosureCode: res.data.enclosureCode, // 唯一标识
          directoryCode:retrievedForm.value.directoryCode,
          directoryName:retrievedForm.value.name,
          enclosureSize:enclosureSize,
          enclosureClassification:1,
          creator:{
            id: userInfo.value.userId,
            name: userInfo.value.name,
            userName: userInfo.value.userName,
            organId: userInfo.value.organId || '',
            organName: userInfo.value.organName || ''
          }
        })
      }else{
        ElMessage.error(res?.message)
      }
    }
    return files
  }

  /**
   * 点击查询
   */
  const searchChange = (data: any) => {
    // 这里也应该查第一页
    pager.currentPage = 1;
    getList();
  };

  // 排序
  const sortChange=(data:any)=>{
    console.log(data);
    pager.currentPage = 1;
    const method = data.order==='descending'?'desc':'asc';
    order.value=[{ column:
      data.prop=='code'?'code':
      data.prop=='enclosureSize'?'enclosure_size':
      data.prop=='enclosureVersion'?'enclosure_version':
      data.prop=='createTime'?'create_time':
      data.prop, method, }];
    getList()
  };

  //清空
  const searchReset = () => {
    retrievedForm.value = {
      fileName: undefined,
      versionNumber: undefined,
      fileCode: undefined,
      enclosureType: undefined,
      timeStr: [],
      directoryCode:retrievedForm.value.directoryCode,
      enclosureClassification:1,
    }
    order.value = [{"column": "create_time","method": "desc"}];// 清空排序？？？
    pager.currentPage = 1;
    pager.pageSize = 10;
    getList();
  };

  const showBtn = ref(false);
  const handleNodeClick=(row:any)=>{
    retrievedForm.value.directoryCode = row.id;
    retrievedForm.value.name = row.name;
    getList();
  };
  const directoryCode=ref(null)
  const treeRef1=ref(null)
  const handleNodeClick1=(data:any,checked:any, node:any)=>{
    if(checked){
      treeRef1.value.setCheckedKeys([data.id]);
      directoryCode.value=data.id
    }
    // console.log(" directoryCode.value", directoryCode.value)
    //directoryCode.value=row.id
  }
  //获取信息列表
  const getList= async () => {
    if(retrievedForm.value.directoryCode==undefined){
      return
    }
    const payload = {
      pageNum: pager.currentPage,
      pageSize: pager.pageSize,
      condition: {
        ...retrievedForm.value,
        createTimeBegin: undefined,
        createTimeEnd: undefined,
        order : order.value
      }
    };
    if (!retrievedForm.value.timeStr || retrievedForm.value.timeStr?.length == 0) {
      payload.condition.createTimeBegin = undefined;
      payload.condition.createTimeEnd = undefined;
    } else {
      payload.condition.createTimeBegin = retrievedForm.value.timeStr[0];
      payload.condition.createTimeEnd = retrievedForm.value.timeStr[1]
    }
    loading.value = true;

    const res = await enclosurePageList(payload);
    if(res?.code=='1'){
      tableData.value=[]
      tableData.value=res.data.list;
      const arr = Object.keys(tableData.value);
     // arr.length == 0 ? showBtn.value = true : showBtn.value = false;
      pager.total = res.data.total;
      pager.pageCount =
        Math.ceil(pager.total / pager.pageSize) === 0
          ? 1
          : Math.ceil(pager.total / pager.pageSize);
    }
    loading.value = false;
  };

  // 分页
  const sizeChange = (size: number) => {
    // 感觉这里要查第一页？？？？？
    pager.currentPage = 1;
    pager.pageSize = size;
   // order.value = [];// 清空排序？？？
    getList()
  };
  const currentChange = (value: number) => {
    pager.currentPage = value;
    getList()
  };
  const onGetResource= async () => {
    const res = await getResource("enclosure_type");
    if(res.code=='1'){
      fileTypes.value=res.data.properties.meta
    };
  };

  /**
   * 导出
   */
  const exportLoading = ref(false);
  const exportLoading1 = ref(false);
  const exportFn = () =>{
    if(retrievedForm.value.directoryCode==undefined){
      ElMessage.error(`请选择导出的目录`)
      return
    }
    const directoryCode = retrievedForm.value.directoryCode;
    const enclosureClassification = retrievedForm.value.enclosureClassification;
    const enclosureType = retrievedForm.value.enclosureType;
    const fileCode = retrievedForm.value.fileCode;
    const fileName = retrievedForm.value.fileName;
    const timeStr = retrievedForm.value.timeStr;
    const versionNumber = retrievedForm.value.versionNumber;
    const list=[];
    if(directoryCode!=undefined)list.push("directoryCode="+directoryCode)
    if(enclosureClassification!=undefined)list.push("enclosureClassification="+enclosureClassification)
    if(enclosureType!=undefined)list.push("enclosureType="+enclosureType)
    if(fileCode!=undefined)list.push("fileCode="+fileCode)
    if(fileName!=undefined)list.push("fileName="+fileName)
    if(versionNumber!=undefined)list.push("versionNumber="+versionNumber)
    if(timeStr.length>0)list.push("createTimeBegin="+timeStr[0]+"&createTimeEnd="+timeStr[1])
    exportLoading1.value=true;
    exportFile(list.join("&")).then((res)=>{
        console.log(res);
      // const link = document.createElement("a");
      // const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
      // link.style.display = "none";
      // link.href = URL.createObjectURL(blob);
      // link.setAttribute("download", "导出表格.xlsx"); // 报表名称可自定义
      // document.body.appendChild(link)
      // link.click()
      // document.body.removeChild(link)


      const fileName = "合约文件"  + ".xlsx"; // 自定义文件名
      const blob = new Blob([res], {
        type: "application/vnd.ms-excel;charset=utf-8", // 文件格式
      });
      const link = document.createElement("a"); // 创建下载链接
      link.href = URL.createObjectURL(blob);
      link.download = `${fileName}`;
      link.click();
      URL.revokeObjectURL(link.href);
      link.remove();

    }).finally(()=>{
      exportLoading1.value=false;
    })

  };
  //下载文件
  const download=(row:any)=>{
    var suffix = row.path?.match(/.[^.]+$/)[0];
    const x = new window.XMLHttpRequest();
    x.open("GET", row.path, true);
    x.responseType = "blob";
    x.onload = () => {
      const url = window.URL.createObjectURL(x.response);
      const a = document.createElement("a");
      a.href = url;
      a.download = row.enclosureName+suffix;
      a.click();
    };
    x.send();

  }
  //历史版本弹窗
  const handleHistory= async (row: any) => {
    centerDialogVisible2.value=true
    const res = await getHistory(row.id)
    historyData.value=res.data
  }
  onMounted(()=>{
    onGetResource();
    companyDataFn();
  })
</script>

<style lang="less" scoped>
  ::-webkit-scrollbar {
    width: 5px;
    height: 5px;
  }
  ::-webkit-scrollbar-thumb {
    background-color: #dddee0;
  }
  .container {
    ::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
      width: 100%;
    }
    ::v-deep .el-tree-node:focus > .el-tree-node__content {
      background-color: #5daaf0; //背景色
      width: 100%;
    }
    .title-span {
      display: block;
      width: 100%;
      background: #fff;
      span {
        display: block;
        border-left: 5px solid #2e7cf1;
        color: #353A42;
        font-size: 0.75rem;
        font-weight: bold;
        padding-left: 5px;
      }
    }
    .tableColumns {
      display: flex;
      .left-tree {
        min-width: 240px;
        background-color: #fff;
        margin: 0 15px 15px;
        padding: 15px;
        overflow-x: auto;
        height: 550px;
        border-radius: 8px;
      }
      ::v-deep .el-tree-node > .el-tree-node__children {
        overflow: visible !important;
      }
      .right-columns {
        flex: 1;
        background-color: #fff;
        margin-right: 15px;
        padding: 15px;
        height: 550px;
        border-radius: 8px;
        .btn-box {
          text-align: right;
        }
      }
    }
    ::v-deep .upload-demo .el-upload-list {
      max-height: 100px;
      overflow-y: auto;
    }
  }
</style>
